package com.zxh.blog.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zxh.blog.R
import com.zxh.blog.adapter.CategoryPagerAdapter
import com.zxh.blog.bean.Category
import com.zxh.blog.bean.ResponseJson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException


class CategoryFragment : Fragment() {

    private lateinit var mTabLayout: TabLayout

    private lateinit var mViewPager: ViewPager

    private val mBaseURL = "http://43.140.201.43:7777/category/getCategoryList"

    private var mCategoryList = ArrayList<Category>()

    private lateinit var view: View
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        view = inflater.inflate(R.layout.fragment_category, container, false)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mTabLayout = view.findViewById(R.id.tab_layout)
        mViewPager = view.findViewById(R.id.viewPager)
        CoroutineScope(Dispatchers.Main).launch {
            // 获取分类列表
            getCategoriesByOkhttp()
            // 在这里处理返回的分类列表
            // 这里可以更新 UI 或执行其他需要在主线程中进行的操作
            // 使用 childFragmentManager 替代 supportFragmentManager
            val adapter = CategoryPagerAdapter(mCategoryList, childFragmentManager)
            for (category in mCategoryList) {
                val fragment = ArticleListFragment.newInstance(category.id)
                adapter.addFragment(fragment)
                mTabLayout.addTab(mTabLayout.newTab().setText(category.name))
            }
            mViewPager.adapter = adapter

            mTabLayout.setupWithViewPager(mViewPager)
        }

    }


    /**
     *  获取分类列表
     */
    private suspend fun getCategoriesByOkhttp() {
        withContext(Dispatchers.IO) {
            // 通过后端接口请求数据，返回分类列表
            val client = OkHttpClient()
            val request = Request.Builder()
                .url(mBaseURL)
                .build()
            try {
                // 发送请求并获取响应
                val response = client.newCall(request).execute()

                // 检查响应是否成功
                if (response.isSuccessful) {
                    // 获取响应体的内容
                    val responseBody = response.body?.string()
                    if (responseBody != null) {
                        parseJSONWithGSON(responseBody)
                    } else {
                        throw IOException("Unexpected response code: \${response.code}")
                    }
                } else {
                    throw IOException("Unexpected response code: \${response.code}")
                }
            } catch (e: IOException) {
                e.printStackTrace()
                // 处理错误情况，可以返回一个默认的空列表或其他适当的处理方式
                emptyList<Category>()
            }
        }
    }

    private fun parseJSONWithGSON(responseData: String) {
        val gson = Gson()
        val typeToken = object : TypeToken<ResponseJson<List<Category>>>() {}.type
        val data: ResponseJson<List<Category>> = gson.fromJson(responseData, typeToken)
        mCategoryList = data.data as ArrayList<Category>
    }


}